from django.http import HttpResponseRedirect
from django.utils.translation import gettext as _
from rest_framework.decorators import api_view
from rest_framework.response import Response

from apps.app_aai_proxy.oidc_client import OIDCClient, AAIProxyHelper


@api_view(['GET'])
def redirect_aai_authentication(request, *arge, **kwargs):
    """
    重定向至aai进行认证
    """
    nonce = "123"   # 传递此参数
    scope = "openid email profile"
    end_redirect_url = request.query_params.get("clientUrl")
    if not AAIProxyHelper.allow_client(end_redirect_url):
        return Response(data={'message': _('回调服务域名无权访问，请联系系统管理员')})

    callback_url = AAIProxyHelper.get_aai_proxy_callback_url()
    try:
        auth_url = OIDCClient.build_client().build_authentication_url(
            redirect_url=callback_url, state=end_redirect_url, nonce=nonce, scope=scope)
    except Exception as e:
        return Response(data={'message': _('请求AAI错误，构建登录url失败。') + str(e)})

    return HttpResponseRedirect(redirect_to=auth_url)


@api_view(['GET'])
def redirect_code2app(request, *arge, **kwargs):
    """
    aai认证完成后的proxy的回调url，重定向到前端的回调地址，并带着code
    """
    code = request.query_params.get("code")
    state = request.query_params.get("state")

    if not code:
        return Response(data={'message': _('AAI登录回调URL错误！缺少必要的参数:code')})

    if not state:
        return Response(data={'message': _('AAI登录回调URL错误！缺少必要的参数:state')})

    redirect_to = AAIProxyHelper.replace_query_params(url=state, params={'code': code})
    return HttpResponseRedirect(redirect_to=str(redirect_to))
